<template>
  <div class="container">
    <div class="area">
      <!--
      1. model 双向绑定
      2. rules 配置“标星”的校验规则： model.prop = rules.key
      3. ref 通过该属性选择指定的表单
      -->
      <!-- model：表单检验时必填。 因为在表单检验时，校验器获取的值为：model.prop，该值需要和v-model绑定的值一样，
       否则校验规则一直提示该属性不能为空。 ref：标识需要校验的组件 ，rules 校验使用的规则   -->
      <el-form :model="form" ref="checkForm" :rules="rules" label-width="80px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题"/>
        </el-form-item>
        <el-form-item label="缩略图" prop="url">
          <el-upload
            class="avatar-uploader"
            :action="uploadServer"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章类型" prop="type">
          <el-input v-model="form.type" placeholder="请输入文章类型（原创/转载）"/>
        </el-form-item>
        <el-form-item label="文章渠道" prop="channel">
          <el-select v-model="form.channel" placeholder="请选择渠道" style="width: 100%">
            <el-option label="公共板块" value="0"></el-option>
            <el-option label="代理体系" value="1"></el-option>
            <el-option label="技能培训" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作者" prop="auth">
          <el-input v-model="form.auth" placeholder="请输入作者"/>
        </el-form-item>
        <el-form-item label="阅读量" prop="userRead">
          <el-input v-model="form.userRead" placeholder="请输入阅读量"/>
        </el-form-item>
        <el-form-item label="工作室" prop="area">
          <el-input v-model="form.area" placeholder="请输入工作室"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="排序不能为空"/>
        </el-form-item>
        <el-form-item label="时间" prop="createTime">
          <el-input v-model="form.createTime" placeholder="时间格式(yyyy年mm月dd日 HH:mm)"/>
        </el-form-item>

        <!--         prop="fujian" 该属性限制了，必须要校验的KEY，校验值取自 :model="form" 中对应的key-->
        <el-form-item label="上传附件" prop="fujian">
          <el-upload
            :action="uploadServer"
            :on-success="fujianSuccess"
            :on-remove="remove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <!--            <div slot="tip" class="el-upload__tip">只允许上传PDF文件</div>-->
          </el-upload>
        </el-form-item>
        <el-form-item label="文章内容" prop="txt">
          <div style="border: 1px solid #ccc;height: 600px">

            <!-- :editor="editor" 动态读取编辑器实例-->
            <Toolbar
              style="border-bottom: 1px solid #cccccc;height: 50px;"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <!--编辑器区域-->
            <Editor
              style="height: 550px;  overflow-y: hidden;"
              v-model="html"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <!--        <el-button @click="cancel">取 消</el-button>-->
      </div>
    </div>
  </div>
</template>
<script>
// 引入工具栏和编辑器区域
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

/* 工具栏配置项 */
import {DomEditor, IModuleConf} from '@wangeditor/editor'

/* 编辑器配置项 */
import {addMiniWenzhang, getMiniWenzhang, updateMiniWenzhang} from '@/api/mini/wenzhang'
import config from '@/utils/config'

export default {
  name: 'MyEditor',
  components: {Editor, Toolbar},
  data() {
    return {
      uploadServer: config.uplaodServer,
      imgPrex: config.imgPrefx,
      imageUrl: '',
      mode: 'default', /* 工具栏模式  simple*/
      editor: null, /* 编辑器实例 */
      html: '',
      toolbarConfig: {
        //toolbarKeys: [ "blockquote"], /* 工具栏上只显示的菜单 */
        excludeKeys: ['uploadImage', 'uploadVideo', 'fullScreen'] /* 工具栏上排除的菜单(只需要考虑具体的key,无需关注对应的结构) */
      },
      editorConfig: {
        placeholder: '请输入内容...',
        // autoFocus: false,
        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
          'uploadImage': {
            server: '/api/upload'
          }
        }
      },
      form: {
        id: '',
        title: '',
        sort: '',
        url: '',
        type: '',
        txt: '',
        auth: '',
        userRead: '',
        area: '',
        channel: '0',
        createTime: '2024年04月11日 18:43',
        fujian: '', // 附件名称
        fujianurl: '' // 附件对应的url
      },
      fileList: [],
      rules: {
        title: [
          {required: true, message: '文章标题不能为空', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '文章类型（原创，转载）不能为空', trigger: 'blur'}
        ],
        channel: [
          {required: true, message: '渠道不能为空', trigger: 'blur'}
        ],
        auth: [
          {required: true, message: '作者不能为空', trigger: 'blur'}
        ],
        userRead: [
          {required: true, message: '阅读量不能为空', trigger: 'blur'}
        ],
        area: [
          {required: true, message: '工作室不能为空', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '商品排序不能为空', trigger: 'blur'}
        ],
        createTime: [
          {required: true, message: '时间不能为空', trigger: 'blur'}
        ],
        url: [
          {required: true, message: '缩略图不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    // 获取路由传值
    var _this = this
    console.info(_this.$route)
    _this.paramsId = _this.$route.params.keyId
    if (_this.paramsId) {
      getMiniWenzhang(_this.paramsId).then(function (res) {
        if (200 === res.code) {
          const data = res.data
          _this.form.id = data.id
          _this.form.sort = data.sort
          _this.form.title = data.title
          _this.form.url = data.url
          _this.form.type = data.type
          _this.form.txt = data.txt
          _this.form.auth = data.auth
          _this.form.userRead = data.userRead
          _this.form.area = data.area
          _this.form.channel = data.channel
          _this.form.createTime = data.createTime
          _this.imageUrl = _this.imgPrex + data.url
          _this.form.fujian = data.fujian
          //_this.form.fujianurl = _this.imgPrex + data.fujianurl
          _this.form.fujianurl = data.fujianurl
          // 查询后的附件页面渲染，并添加文件访问前缀
          if (undefined != data.fujian && '' != data.fujian && undefined != data.fujianurl && '' != data.fujianurl) {
            var obj = new Object();
            obj['name'] = data.fujian;
            obj['url'] = data.fujianurl; // 附件的相对路径
            _this.fileList.push(obj)
          }
          // 设置编辑器的html片段内容
          _this.editor.setHtml(data.txt)
        }
      })
    }
  },
  mounted() {
    //  延时获取编辑器信息，确保编辑器初始化成功
    setTimeout(() => {
      /* 1. 通过编辑器实例获取所有配置 */
      console.log("获取编辑器所有配置-->", this.editor.getConfig());
      console.log("获取编辑器所有菜单-->", this.editor.getAllMenuKeys())
      //console.log("查看指定菜单的配置-->",this.editor.getMenuConfig('uploadImage'))
      console.log("查看指定菜单的配置-->", this.editor.getMenuConfig("lineHeight"))

      console.log("2121212121-->", this.editor.getConfig().MENU_CONF.lineHeight)


      /* 2. 获取工具栏配置 */
      const toolbar = DomEditor.getToolbar(this.editor)
      const curToolbarConfig = toolbar.getConfig()
      console.log(curToolbarConfig.toolbarKeys) // 排序和分组

      // 初始化 MENU_CONF 属性
      // this.html = '<p>Ajax 异步设置内容 HTML</p>'
    }, 1500)
  },
  methods: {
    onCreated(editor) { // 创建编辑器实例
      this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
    },
    onChange(editor) {
      console.log('onChange', editor.getHtml()) // onChange 时获取编辑器最新内容
      this.form.txt = editor.getHtml()
    },
    getEditorText() {  // 读取编辑器的内容（文本）
      const editor = this.editor
      if (editor == null) return
      console.log(editor.getText()) // 执行 editor API
    },
    printEditorHtml() {  // 读取编辑器的内容（html片段）
      const editor = this.editor
      if (editor == null) return
      console.log(editor.getHtml()) // 执行 editor API
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.form.url = res.msg
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    submitForm() {
      // 1. 校验表单的必填项都完成填写
      var _this = this
      _this.$refs['checkForm'].validate(valid => {
        if (valid) {
          if (!_this.editor.getText()) {
            _this.$message({
              showClose: true,
              message: '文章内容不能为空',
              type: 'warning'
            })
            return
          }
          _this.form.txt = _this.editor.getHtml()
          addMiniWenzhang(this.form).then(response => {
            console.log(response)
            if (200 === response.code) {
              _this.$message({
                showClose: true,
                message: '操作成功',
                type: 'success'
              })
              setTimeout(function () {
                _this.$router.push('/mini/wenzhang')
              }, 3000)
            }
          })
        }
      })
    },
    handleExceed() {
      console.warn("文件单次上传超限")
    },
    fujianSuccess(resp, event) {
      var _this = this;
      console.info(event.name)
      console.info(event.response.msg)

      _this.form.fujian = event.name; // 附件名称
      _this.form.fujianurl = event.response.msg; // 附件的相对路径

      // todo, 当前设置只支持单文件，
      _this.fileList = [];
      var obj = new Object();
      obj['name'] = _this.form.fujian;
      obj['url'] = _this.form.fujianurl;
      _this.fileList.push(obj)

    },
    remove(ev,aa){ // 文件移除
      console.info("文件移除：-->",ev.url)
      var _this = this;
      _this.form.fujian = ''
      _this.form.fujianurl = ''
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁 editor ，重要！！！
  },

}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped>
.container {
  width: 100%;
  /*border: solid 1px red;*/
  display: flex;
  justify-content: center;
}

.area {
  margin-top: 10px;
  width: 90%;
  /* border: solid 1px blue;*/
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>


